package com.zhang.goods.service;

import com.zhang.common.util.time.TimeUtils;
import com.zhang.goods.entity.SkuInfo;
import com.zhang.warehouse.dto.FinishDto;
import com.zhang.warehouse.dto.purchaseDetailsItem;
import com.zhang.warehouse.entity.Purchase;
import com.zhang.warehouse.entity.PurchaseDetail;
import com.zhang.warehouse.entity.WareSku;
import com.zhang.warehouse.service.IPurchaseDetailService;
import com.zhang.warehouse.service.IPurchaseService;
import com.zhang.warehouse.service.IWareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 所有关于库存和商品模块两者的业务类
 *
 * @author hongmizfb
 * @date 2023/10/23
 */
@Service
public class WareAndSkuService {
    @Autowired
    private IPurchaseDetailService purchaseDetailService;
    @Autowired
    private IWareSkuService wareSkuService;
    @Autowired
    private IPurchaseService purchaseService;
    @Autowired
    private ISkuInfoService skuInfoService;

    public void finishPurchase(FinishDto finishDto) {
//        改变采购项的状态
        boolean flag = true;
        for (purchaseDetailsItem purchaseDetail : finishDto.getPurchaseDetails()) {
            if (purchaseDetail.getStatus() == 4) {
                flag = false;
            }
//            TODO
//             1:此处有一个功能未实现：将采购失败的原因存入数据库中，
//             2:有时候，采购会出现采购数量没完全达标，可能只采购了一些，这个功能后续可以考虑实现
            else {
                PurchaseDetail detail = new PurchaseDetail();
                detail.setId(purchaseDetail.getPurchaseDetailId());
                detail.setStatus(purchaseDetail.getStatus());
                purchaseDetailService.updateById(detail);
                //        将成功采购的采购需求进行入库
                Purchase byId = purchaseService.getById(finishDto.getPurchaseId());
                PurchaseDetail detailInfo = purchaseDetailService.getById(detail);
//              TODO  注意，此处的库存是直接获取的采购项的库存指标，如果没有完全完成，此处代码需要更改
                System.out.println("库存:"+detailInfo.getSkuNum());
                SkuInfo skuInfo = skuInfoService.getById(detailInfo.getSkuId());
                wareSkuService.addStock(detailInfo.getSkuId(), detailInfo.getWareId(),detailInfo.getSkuNum(), skuInfo.getSkuName());
            }
        }
        Purchase purchase = new Purchase();
        purchase.setId(finishDto.getPurchaseId());
        purchase.setStatus(4);//有异常
        purchase.setUpdateTime(TimeUtils.getLocalDateTimeStr());
        if (flag) {
            purchase.setStatus(3);//已完成
        }
        //        改变采购单的状态
        purchaseService.updateById(purchase);
    }
}
